const route = require('koa-router')();
const User = require('../../model/user/user.js')
const request = require('../../utils/request')
const jwt = require('jsonwebtoken')
const format = require('../../utils/formatTime.js')
// let payload = {
//     userid:findinfo.user_id
// }
// let sign = 'book';
// let options = {
//     expiresIn:'360 days'
// }
// let token = jwt.sign(payload,sign,options)
route.post('/wx_login',async(ctx,next)=>{
    console.log(new format(new Date('2020-10-01')).theWeek())
    let requestData = ctx.request.body
    let token = ''
    let openid = ''
    let user_info = ''
    // 获取token
    await request(`https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid=wx24910ad4879ea2c0&secret=8f2ec2866d69b4f1d9a4c5e38ee59730`).then(res=>{
        token = JSON.parse(res.body).access_token
    })
    // 获取openid
    await request(`https://api.weixin.qq.com/sns/jscode2session?appid=wx24910ad4879ea2c0&secret=8f2ec2866d69b4f1d9a4c5e38ee59730&js_code=${requestData.code}`).then(res=>{
        openid = JSON.parse(res.body).openid
    })
    let find = await User.find({openid})
    let findAll = await User.find()
    let user_id = 100000
    if(findAll.length!=0){
        user_id = findAll[findAll.length-1].user_id+1
    }
    if(find.length==0){//用户表中没有
        await User.create({
            openid,
            sex:requestData.gender,
            user_name:requestData.nickName,
            user_id,
            avatarUrl:requestData.avatarUrl,
        })
    }

    let findAgain = (await User.find({openid}))[0]

    let payload = {
        userid:findAgain.user_id
    }
    let sign = 'book';
    let options = {
        expiresIn:'360 days'
    }
    let jwttoken = jwt.sign(payload,sign,options)
    
    ctx.body = {
        code:200,
        data:{
            token:jwttoken,
            user_id:findAgain.user_id
        }
    }
})
module.exports = route